package quoridor;

import quoridorDecisionMaker.*;

public class QuoridorPlayer implements Player {
	private final PlayerColour playerColour;
	private final DecisionMaker decisionMaker;
	private Board board;
	
	public QuoridorPlayer (DecisionMakerType playerBrainType, PlayerColour newPlayerColour, Board board) {
		playerColour = newPlayerColour;
		this.board = board;
		decisionMaker = determineDecisionMakerType(playerBrainType);
		
	}
	
	private DecisionMaker determineDecisionMakerType(
			DecisionMakerType playerBrainType) {
		
		switch (playerBrainType) {
			case HUMAN: 
				return new HumanDecisionMaker(board, playerColour);
			case DUMB_AI:
				return new AIDecisionMakerDumb(board);
			case SMART_AI:
				return new AIDecisionMakerSmart(board);
			case RANDOM_AI: 
				return new RandomDecisionMaker(board);
			default: return null;
		}
	}

	public Action takeTurn() {
		String oldGameHistory = board.getHistory();
		Action decisionMakerAction = null;
		boolean finished = false;
		
		while (!finished) {
			try {
				decisionMakerAction = decisionMaker.getAction();
				//check to guarantee the AI has not altered board
				assert(board.getHistory().equals(oldGameHistory));
				
				if (decisionMakerAction.getType() == ActionType.MOVE) {
					if (board.validateMove(decisionMakerAction.getMove())) {
						board.makeMove(decisionMakerAction.getMove());
						finished = true;
					} else {
						QuoridorDisplay.instance().invalidMove();
					}
				} else {
					finished = true;
				}
			} catch (Exception e) {
				return null;
			}
		}
		return decisionMakerAction;
	}

	public PlayerColour getPlayerColour() {
		return playerColour;
	}

}
